/*
 * Copyright 2009 Armando Blancas
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package taskgraph.channels;

import java.io.EOFException;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

import taskgraph.Config;
import taskgraph.ports.BooleanInputPort;
import taskgraph.ports.BooleanOutputPort;


/**
 * A channel that transports boolean values. 
 * 
 * @author Armando Blancas
 */
public class BooleanChannel {
	
	private static final int DEFAULT_BUFFER_SIZE = Config.get().channelCapacity();
	
	private final PipedOutputStream output;
    private final PipedInputStream input;
    private final BooleanOutputPort outputPort;
    private final BooleanInputPort inputPort;
    
    
    /**
     * Creates a channel with the default buffer size.
     */
    public BooleanChannel() {
    	this(DEFAULT_BUFFER_SIZE);
    }
    
    /**
     * Creates a channel with the passed buffer size.
     * 
     * @param bufferSize The buffer capacity in bytes. 
     */
    public BooleanChannel(final int bufferSize) {
        if (bufferSize <= 0) {
            throw new IllegalArgumentException("BooleanChannel bufferSize <= 0");
         }
        
		try {
			output = new PipedOutputStream();
			input = new PipedInputStream(output, bufferSize);
			outputPort = new OutputPort();
			inputPort = new InputPort();
		} catch (IOException e) {
			throw new Error(e);
		}
    }
    
    /**
     * Gets a reference to the output port.
     * 
     * @return An output interface to this channel.
     */
    public BooleanOutputPort getOutputPort() {
    	return outputPort;
    }
    
    /**
     * Gets a reference to the input port.
     * 
     * @return An input interface to this channel.
     */
    public BooleanInputPort getInputPort() {
    	return inputPort;
    }

    /**
     * A private implementation of the boolean output port. It has direct 
     * access to this channel and the boolean input port. Instances of this
     * class are published through the BooleanOutputPort interface. 
     */
    private class OutputPort implements BooleanOutputPort {
    
		@Override
		public BooleanOutputPort write(boolean b) throws IOException {
			output.write(b ? 1 : 0);
			return this;
		}
	
		@Override
		public BooleanOutputPort write(boolean[] b) throws IOException {
			if (b == null) {
				throw new NullPointerException("b == null");
			}
			if (b.length > 0) {
				for (boolean element : b) {
					output.write(element ? 1 : 0);
				}
			}
			return this;
		}
	
		@Override
		public BooleanOutputPort write(boolean[] b, int off, int len) 
		throws IOException {
			if (b == null) {
				throw new NullPointerException("b == null");
			}
			if (b.length > 0) {
				byte[] bytes = new byte[b.length];
				for (int count = len, i = off; count > 0; --count, ++i) {
					bytes[i] = b[i] ? (byte) 1 : 0;
				}
				output.write(bytes, off, len);
			}
			return this;
		}

		@Override
		public void close() {
			try {
				output.close();
			} catch (IOException e) {
				// best effort
			}
		}
	
    }

    /**
     * A private implementation of the boolean input port. It has direct 
     * access to this channel and the boolean output port. Instances of this
     * class are published through the BooleanInputPort interface. 
     */
    private class InputPort implements BooleanInputPort {
	
		@Override
		public boolean read() throws IOException {
			int value = input.read();
			if (value == -1) {
				throw new EOFException("EOF on input port");
			}
			return (value != 0);
		}
	
		@Override
		public int read(boolean[] b) throws IOException {
			return read(b, 0, b.length);
		}
	
		@Override
		public int read(boolean[] b, int off, int len) throws IOException {
			if (b == null) {
				throw new NullPointerException("b == null");
			}
			if (b.length == 0) {
				return 0;
			}
			byte[] bytes = new byte[b.length];
			int count = input.read(bytes, off, len);
			while (len > 0) {
				b[off] = (bytes[off] != 0);
				++off;
				--len;
			}
			return count;
		}
	
		@Override
		public int skipBooleans(int n) throws IOException {
	    	if (n < 0)
	    		throw new IllegalArgumentException("n is negative");
	    	if (n == 0)
	    		return 0;
	    	int toSkip = Math.min(n, input.available());
	    	byte[] f = new byte[toSkip];
	    	return input.read(f);
		}
	
		@Override
		public void close() {
			try {
				input.close();
			} catch (IOException e) {
				// best effort
			}
		}
		
	}

}
